<template>
  <el-container class="friends_tas">
    <el-main>
      <el-card shadow="never" class="selectCard searchColumn">
        <el-form label-position="right" label-width="6rem">
          <el-row :gutter="40">
            <el-col :span="8">
              <el-form-item label="标签组名：">
                <el-input v-model="searchParams.groupName" placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="8" style="float: right;">
              <search-button :default-params="searchParams" @refreshParams="refreshParams" @getList="getList" />
            </el-col>
          </el-row>

        </el-form>
      </el-card>
      <el-card shadow="never" class="commercia-tenant-list-title tableCard">
        <vxe-toolbar>
          <template v-slot:buttons>
            <el-button type="primary" icon="el-icon-plus" size="small" @click="openModal('', 1, false)">新增</el-button>
          </template>
          <template v-slot:tools>
            <vxe-button class="tool-btn" type="text" size="small" icon="el-icon-download" @click="syncFriendsTagsFromWx()">同步客户标签</vxe-button>
            <vxe-button class="tool-btn" type="text" size="small" icon="el-icon-refresh" @click="getList()">刷新</vxe-button>
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTree"
          border
          stripe
          resizable
          highlight-hover-row
          :loading="loading"
          :auto-resize="true"
          :data="activitiesList"
          height="420"
          :print-config="{}"
        >
          <vxe-table-column type="seq" align="center" width="50" title=" " />
          <vxe-table-column field="groupName" title="标签组名" width="220" />
          <vxe-table-column field="tagsNameList" title="标签" min-width="220">
            <template slot-scope="scope">
              <span>
                <el-tag v-for="tag in scope.row.tagsList" :key="tag.id" style="margin-left:5px;margin-bottom: 5px;">{{ tag.tagsName }}</el-tag>
              </span>
            </template>
          </vxe-table-column>
          <vxe-table-column field="syncStatusDesc" width="80" align="center" title="同步状态" />
          <vxe-table-column field="status" width="80" align="center" title="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" :inactive-value="0" :active-value="1" active-text inactive-text @change="changeState(scope)" />
            </template>
          </vxe-table-column>
          <vxe-table-column title="操作" fixed="right" width="150" align="center" slots="default">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="openModal(scope.row.id, 2, true)">查看</el-button>
              <el-button v-if="scope.row.status != 1" type="text" size="mini" @click="openModal(scope.row.id, 2, false)">编辑</el-button>
              <el-button v-if="scope.row.status != 1" type="text" size="mini" @click="del(scope.row.id)">删除</el-button>
              <el-button v-if="scope.row.syncStatus != 1" type="text" size="mini" @click="syncToWxCp(scope.row.id)">同步</el-button>
            </template>
          </vxe-table-column>
        </vxe-table>
        <vxe-pager
          :current-page.sync="tableCurrentPage"
          :page-size.sync="pageSize"
          :total="total"
          :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'FullJump', 'Total']"
          @page-change="getList()"
        />
      </el-card>
    </el-main>
    <el-dialog v-if="dialogVisible" width="30%" title="添加标签" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form ref="ruleForm" :model="params" :rules="rules" label-width="6rem">
        <el-row :gutter="40">
          <el-col :span="24">
            <el-form-item prop="groupName" label="标签组名：">
              <div style="width:80%;">
                <el-input v-model="params.groupName" :disabled="diabledEdit" />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="tagsList" label="标签：">
              <div class="tags-container">
                <div v-for="(item,index) in params.tagsList" :key="index" class="tags-list">
                  <div>
                    <el-input v-model="item.tagsName" size="small" :disabled="diabledEdit" />
                  </div>
                  <div v-if="!diabledEdit">
                    <i v-if="params.tagsList.length > 1 " class="iconfont icon-minus" @click="removeTags(index)" /><i v-if="params.tagsList.length-1 === index" class="iconfont icon-plus" @click="addTags" />
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { syncFriendsTagsList, syncFriendsTagsToWxCp, delFriendsTags, getFriendsTagsPageList, addFriendsTags, modifyFriendsTags, viewFriendsTags, changeFriendsTagsStatus } from '@/api/cop/friends'
import SearchButton from '@/components/SearchButton'

export default {
  components: {
    SearchButton
  },
  data() {
    return {
      activitiesList: [],
      loading: false,
      searchParams: {
        groupName: ''
      },
      tableCurrentPage: 1,
      pageSize: 20,
      total: 0,
      params: {
        groupName: '',
        tagsList: []
      },
      dialogVisible: false,
      diabledEdit: true,
      rules: {
        groupName: [{ required: true, message: '请输入名称', trigger: 'blur' }]
      },
      parentId: '',
      type: 1 // 1 添加 2修改
    }
  },
  created() {
    this.getList()
  },
  methods: {
    syncFriendsTagsFromWx() {
      this.$confirm('确定要从企业微信同步客户标签, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        syncFriendsTagsList().then(res => {
          if (res) {
            this.$message.info('正在从企业微信同步客户标签，请一会儿刷新！')
            this.$nextTick(() => {
              this.getList()
            })
          }
        })
      }).catch(() => {
        this.$message.info('取消操作')
      })
    },
    syncToWxCp(id) {
      this.$confirm('确定要从企业微信同步欢迎语, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        type: 'warning'
      }).then(() => {
        syncFriendsTagsToWxCp({ id }).then(res => {
          if (res) {
            this.$alert('正在同步客户标签到企业微信，请稍候刷新！', '消息提示', { confirmButtonText: '我知道了', center: true, callback: action => {} })
            this.$nextTick(() => {
              this.getList()
            })
          }
        })
      }).catch(() => {
        this.$message.info('取消操作')
      })
    },
    refreshParams(params) {
      this.searchParams = {}
    },
    openModal(id, type, bool) {
      this.diabledEdit = bool
      this.operationType = type
      this.dialogVisible = true
      if (type === 2) {
        viewFriendsTags({ id })
          .then(response => {
            if (response) {
              this.params = response
              this.params.tagsList = response.tagsList
            }
          })
      } else {
        this.params = {
          groupName: '',
          tagsList: [
            {
              tagsName: '',
              sort: 0
            }
          ]
        }
      }
    },
    getList() {
      getFriendsTagsPageList({
        pageNum: this.tableCurrentPage,
        pageSize: this.pageSize,
        ... this.searchParams
      }).then(response => {
        if (response) {
          this.activitiesList = response.records
          this.total = response.total
        }
      })
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.operationType === 1) {
            addFriendsTags(this.params).then(response => {
              this.$message.success('添加成功')
              this.dialogVisible = false
              this.getList()
            })
          } else {
            modifyFriendsTags(this.params).then(response => {
              this.$message.success('修改成功')
              this.dialogVisible = false
              this.getList()
            })
          }
        }
      })
    },
    del(id) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delFriendsTags({ id }).then(response => {
          this.$message.success('删除成功')
          this.getList()
        })
      })
    },
    changeState(scope) {
      this.activitiesList[scope.seq - 1].status = scope.row.status === 1 ? 0 : 1
      changeFriendsTagsStatus({
        id: scope.row.id,
        status: scope.row.status === 1 ? 0 : 1
      }).then(response => {
        this.activitiesList[scope.seq - 1].status = scope.row.status === 1 ? 0 : 1
        this.$message.success(scope.row.status === 0 ? '禁用成功' : '启用成功')
      })
    },
    addTags() {
      this.params.tagsList.push({
        tagsName: '',
        sort: this.params.tagsList.length
      })
    },
    removeTags(index) {
      this.$delete(this.params.tagsList, index)
    }
  }
}
</script>

<style lang="scss">
.friends_tas {
  .tags-container {
    display:inline-block;
    justify-content: flex-start;
    width:100%;
    vertical-align: middle;
    .tags-list {
      display:flex;
      justify-content: left;
      vertical-align: middle;
      align-items:left;
      width:98%;
      >div{
        &:first-child{
          width:80%
          }
      }
      i {
        padding: 0px 5px 0px 5px;
      }
    }
  }
}
</style>
